package cn.arnold.stack;

public class Stack {

    private int maxSize;    //数组（栈）的大小
    private int[] arrayStack;   //数组模拟栈
    private int top = -1;    //栈顶指针，初始化为-1

    // 构造器
    public Stack(int maxSize) {
        this.maxSize = maxSize;
        arrayStack = new int[this.maxSize];
    }

    // 栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满...");
            return;
        }
        top++;
        arrayStack[top] = value;
    }

    // 出栈
    public int pop() {
        int res = 0;
        if (isEmpty()) {
            throw new RuntimeException("栈空...");
        }
        res = arrayStack[top];
        top--;
        return res;
    }

    // 遍历
    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈空...");
            return;
        }
        // 从栈顶开始显示数据
        for (int i = top; i >= 0; i--) {
            System.out.println("arrayStack[" + i + "]=" + arrayStack[i]);
        }
    }

    // 获取栈顶元素
    public String peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈空...");
        }
        String s;
        s = "" + arrayStack[top];
        return s;
    }
}
